<?php
/**
 * Created by PhpStorm.
 * User: ship
 * Date: 2024/12/30
 * Time: 13:37
 */

namespace ShipSun\LaravelRequestResponseJm;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * Class ResponseEncryptMiddleware
 * @package ShipSun\LaravelRequestResponseJm
 */
class ResponseEncryptMiddleware extends BaseMiddleware
{
    public static $response_method = [];

    public function handle(Request $request, \Closure $next)
    {
        $response = $next($request);
        if ($this->isJm($request)) {
            $data = json_decode($response->getContent(), true);
            if (!isset($data['code'])) {
                return $this->encrypter->encrypt($response);
            };
            if (isset($data['code']) && ($data['code'] == 10000 || $data['code'] == 200) && $response instanceof JsonResponse) {
                return $this->encrypter->encrypt($response);
            }
        }
        return $response;
    }

    /**
     * @param Request $request
     * @return bool
     */
    protected function allowMethod(Request $request)
    {
        if (in_array(strtolower($request->getMethod()), static::$response_method)) {
            return true;
        }
        return false;
    }
}